//$URL: http://dasding.googlecode.com/svn/branches/testzeugs/api/src/main/java/de/piratech/dasding/security/UserSecurityContext.java $
//$Id: UserSecurityContext.java 78 2012-10-22 23:03:42Z amuthmann@gmail.com $
package de.piratech.dasding.security;

import de.piratech.dasding.data.User;
import java.security.Principal;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class used to store a user inside of the securitycontext
 * @author deveth0
 */
public class UserSecurityContext implements javax.ws.rs.core.SecurityContext {

  private static final Logger LOG = LoggerFactory.getLogger(UserSecurityContext.class);
  private final User mUser;

  public UserSecurityContext(User pUser) {
    this.mUser = pUser;
  }

  @Override
  public String getAuthenticationScheme() {
    return SecurityContext.BASIC_AUTH;
  }

  @Override
  public Principal getUserPrincipal() {
    return mUser;
  }

  @Override
  public boolean isSecure() {
    return mUser != null;
  }

  @Override
  public boolean isUserInRole(String pRole) {
    LOG.debug("isUserInRole({})", pRole);
    if (mUser == null) {
      // Forbidden
      LOG.debug("user is null");
      Response denied = Response.status(Response.Status.FORBIDDEN).build();
      throw new WebApplicationException(denied);
    }
    try {
      // this user has this role?
      LOG.debug("user has role {}", mUser.getRoles().contains(User.USER_ROLE.valueOf(pRole)));
      return mUser.getRoles().contains(User.USER_ROLE.valueOf(pRole));
    } catch (Exception e) {
      LOG.warn("exception", e);
    }
    return false;
  }
}